package com.laosg.springboot.study.nsq.consumer.config;

import com.github.brainlag.nsq.NSQProducer;
import com.laosg.springboot.study.nsq.consumer.config.properties.NsqProperties;
import com.sproutsocial.nsq.Publisher;
import com.sproutsocial.nsq.Subscriber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by kaimin on 29/4/2019.
 * time : 10:04
 */
@Configuration
public class NsqProductionConfig {

    @Autowired
    private NsqProperties nsqProperties;

//    @Bean  //nsq-client这个jar包提供的client
    public NSQProducer nsqProducer() {
        NSQProducer nsqProducer = new NSQProducer();
        for (int i = 0; i < nsqProperties.getNsqd().getAddresses().size(); i++) {
            nsqProducer.addAddress(nsqProperties.getNsqd().getAddresses().get(i),nsqProperties.getNsqd().getPorts().get(i));
        }
        nsqProducer.start();
        return nsqProducer;
    }
    //让一台nsq机器挂掉之后，备用的就会生效
    @Bean
    public Publisher publisher(){
        //一个生产者，最多向两个nsqd发，一个是主，一个是灾备
        Publisher publisher = new Publisher(
                nsqProperties.getNsqd().getAddresses().get(0)+":"+nsqProperties.getNsqd().getPorts().get(0)
                ,
                nsqProperties.getNsqd().getAddresses().get(1)+":"+nsqProperties.getNsqd().getPorts().get(1)
        );


        return publisher;
    }

    @Bean
    public Subscriber subscriber(){
        Subscriber subscriber = new Subscriber(
                nsqProperties.getNsqlookup().getAddresses().get(0)+":"+nsqProperties.getNsqlookup().getPorts().get(0)
        );

        return subscriber;
    }

}
